package com.yun.zf.admin.controller;


import com.yun.zf.admin.service.ZfCustomerAgentService;
import com.yun.zf.admin.service.ZfCustomerRequirementService;
import com.yun.zf.admin.service.ZfCustomerService;
import com.yun.zf.common.admin.dto.customer.CustomerListDto;
import com.yun.zf.common.admin.model.customer.CooperationMo;
import com.yun.zf.common.admin.model.customer.CustomerBasicMo;
import com.yun.zf.common.admin.model.customer.CustomerReqMo;
import com.yun.zf.common.admin.model.search.CustomerSearchMo;
import com.yun.zf.common.annotation.LogPrint;
import com.yun.zf.common.esRes.CustomerIndexResMo;
import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.redis.RedissonUtils;
import com.yun.zf.system.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 客户资源表 前端控制器
 * </p>
 *
 * @author cj
 * @since 2021-03-30
 */
@RestController
@RequestMapping("/zfCustomer")
@Api(tags = "客户资源管理")
public class ZfCustomerController extends BaseController {
    @Autowired
    private ZfCustomerService customerService;
    @Autowired
    private ZfCustomerRequirementService requirementService;
    @Autowired
    private ZfCustomerAgentService customerAgentService;
    @Autowired
    private RedissonUtils redissonUtils;

    /*  {
          "birthday": "2001-2-11",
              "certMos": [
          {
              "path": "dsgs/test",
                  "url": "dsgs/test/4444.jpg"
          },
          {
              "path": "dsgs1111/test",
                  "url": "dsgs/test/441144.jpg"
          }
    ],
          "certificateNo": "1101000000200233",
              "certificateType": 1,
              "email": "11122@qq.com",
              "name": "孔明",
              "phone": "17777777",
              "sex": "男"
      }*/
    @ApiOperation(value = "客户资源录入")
    @PostMapping(value = "/addCustomerInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    public Response addCustomerInfo(@Validated @RequestBody CustomerBasicMo basicMo) {
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        if (StringUtils.isNotEmpty(basicMo.getId())) {
            customerService.motifyCustomer(basicMo, agentNo, prov, aCode);
        } else {
            customerService.addCustomer(basicMo, agentNo, prov, aCode);
        }
        return Response.success();
    }

    @ApiOperation(value = "查询客户基本信息")
    @PostMapping(value = "/getBasicInfo")
    public Response getBasicInfo(@RequestBody Map<String, String> map) {

        return Response.success(customerService.getBasicInfo(prov, aCode, Long.parseLong(map.get("customerId"))));
    }

    /*{
            "area": "100-140",
                "bedrooms": "3-4",
                "budget": "7000-10000",
                "buidYear": "5-10",
                "bus": "[{\"way\":\"松江1路\",\"stops\":[\"泗泾2站\",\"金地12站\"]}]",
                "business": "[]",
                "cityCode": 420100,
                "createTime": "",
                "customerId": 1377597857109057537,
                "demandType": 1,
                "entrustDate": "",
                "fixtures": "jz",
                "floor": "",
                "hospital": "[]",
                "provinceCode": 42,
                "region": "[]",
                "remark": "",
                "rentType": 0,
                "school": "[]",
                "subway": "[{\"subway\":\"9号线\",\"stations\":[\"泗泾站\",\"九亭站\"]}]",
                "unit": "元"
        }*/
    @ApiOperation(value = "补充客户需求信息")
    @PostMapping("/addCustomerRequirement")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    public Response addCustomerRequirement(@Validated @RequestBody CustomerReqMo reqMo) {

        if (StringUtils.isNotEmpty(reqMo.getId())) {
            requirementService.motifyRequirement(reqMo, prov, aCode);
        } else {
            requirementService.addRequirement(reqMo, prov, aCode);
        }
        return Response.success();
    }

    @ApiOperation(value = "客户资源详情")
    @PostMapping("/customerDetailInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")

    public Response customerDetailInfo(@RequestBody Map<String, String> map) {
        return Response.success(requirementService.getCustomerDetailInfo(Long.parseLong(map.get("customerId")), prov, aCode));
    }


    @ApiOperation(value = "客户需求查看")
    @PostMapping("/getRequirement")
    public Response getRequirement(@RequestBody Map<String, String> map) {
        return Response.success(requirementService.getRequirement(prov, aCode, Long.parseLong(map.get("requirementId"))));
    }

    @ApiOperation(value = "查看手机号码")
    @PostMapping("/getPhoneInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    public Response getPhoneInfo(@RequestBody Map<String, String> map) {
        try {
            //1、 验证是否为维护业务员
            int agentNo = SecurityUtils.getLoginUser().getAgentNo();
            int count = customerAgentService.checkAuthorize(Long.parseLong(map.get("customerId")), agentNo, prov, aCode);
            if (count == 0) {
                return Response.error("无权查看当前客户手机号码");
            }
            String phone = customerService.getPhone(prov, aCode, Long.parseLong(map.get("customerId")));
            Map<String, String> map1 = new HashMap<>();
            map1.put("iphone", phone);
            return Response.success(map1);
        } catch (Exception e) {
            return Response.error("获取失败");
        }
    }


    /* {
        "area": "90-120",
            "bedrooms": "",
            "budget": "",
            "bus": "松江1路",
            "business": "",
            "cityCode": 420100,
            "demandType": "",
            "fixtures": "",
            "floor": "",
            "hospital": "",
            "key": "110123",
            "pageSize": 10,
            "provinceCode": 0,
            "region": "",
            "rentType": "",
            "school": "",
            "startPage": 1,
            "stations": "[\"泗泾站\"]",
            "status": "",
            "stop": "[\"泗泾2站\"]",
            "subway": "9号线"
    }*/
    @ApiOperation(value = "客户资源管理搜索")
    @PostMapping("/searchCustomerInfo")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    public Response searchCustomerInfo(@Validated @RequestBody CustomerSearchMo customerSearchMo) {
        Map<String, Object> map = requirementService.searchCustomer(customerSearchMo, prov, aCode);
        if (map == null) {
            return Response.error("未搜索到数据");
        }
        List<CustomerIndexResMo> sourceList = (List) map.get("records");
        List<Long> ids = new ArrayList<>();
        if (sourceList.size() <= 0) {
            return Response.error("未搜索到数据");
        }
        for (CustomerIndexResMo hmap : sourceList) {
            ids.add(Long.parseLong(hmap.getCustomerId()));
        }
        List<CustomerListDto> list = customerService.getSearchList(prov, aCode, ids);
        map.put("records",list);
        return Response.success(map);
    }


    @ApiOperation(value = "发布")
    @PostMapping("/pushClient")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @LogPrint
    public Response pushClient(@RequestBody Map<String, String> map) {
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        int count = customerAgentService.checkAuthorize(Long.parseLong(map.get("customerId")), agentNo, prov, aCode);
        if (count == 0) {
            return Response.error("非客户维护人，不得进行发布");
        }
        // 当前业务员工号
        requirementService.pushCustomer(prov, aCode, Long.parseLong(map.get("customerId")));
        return Response.success();
    }

    @ApiOperation(value = "推送平台")
    @PostMapping("/pushPlatform")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @LogPrint
    public Response pushPlatform(@RequestBody Map<String, String> map) {
        int agentNo = SecurityUtils.getLoginUser().getAgentNo();
        int count = customerAgentService.checkAuthorize(Long.parseLong(map.get("customerId")), agentNo, prov, aCode);
        if (count == 0) {
            return Response.error("非客户维护人，不得进行推送");
        }
        // 当前业务员工号
        requirementService.pushPlatform(prov, aCode, map.get("customerId"));
        return Response.success();
    }


    @ApiOperation(value = "发起合作")
    @PostMapping("/referCustomers")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @LogPrint
    public Response referCustomers(@RequestBody Map<String, String> map) {
        // 共享资源中浏览的客户维护经纪人的工号和姓名
        String refName = map.get("refName");
        String refNo = map.get("refNo");
        // 1、验证是否为找房经纪人
        int res1 = customerAgentService.isBroker(prov, aCode, Long.parseLong(map.get("customerId")), Integer.parseInt(refNo));
        if (res1 == 0) {
            return Response.error("非委托经纪人，不能进行合作");
        }
        try {
            customerAgentService.referCustomers(prov, aCode, Long.parseLong(map.get("customerId")), Integer.parseInt(refNo), refName);
            return Response.success();
        } catch (Exception e) {
            return Response.error("获取失败");
        }
    }


    @ApiOperation(value = "合作列表查询")
    @PostMapping("/cooperation")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @LogPrint
    public Response cooperation(@RequestBody CooperationMo cooperation) {
        return Response.success(customerAgentService.cooperationList(cooperation, prov, aCode));
    }


    @ApiOperation(value = "同意或者拒绝合作")
    @PostMapping("/operate")
    @PreAuthorize("@ss.hasAnyRoles('agent')")
    @LogPrint
    public Response operate(@RequestBody Map<String, String> map) {
        // 当前业务员工号
        int cn = customerAgentService.acceptOrRefuse(Long.parseLong(map.get("caId")), Integer.parseInt(map.get("ar")), prov, aCode);
        if (cn > 0) {
            return Response.success();
        }
        return Response.error();
    }


    /**
     * 验证当前业务员是否有权限更新当前数据
     *
     * @param customerId
     * @param agentNo
     * @return
     */
    public boolean checkAuthorize(Long customerId, int agentNo, Long provCode, Long cityCode) {
        int res = customerAgentService.checkAuthorize(customerId, agentNo, provCode, cityCode);
        if (res > 0)
            return true;
        return false;
    }


}

